local extension = Package:new("ofl_edition_ex")
extension.extensionName = "est_test"

local U = require "packages/utility/utility"
local UE = require "packages/est_test/utility"

Fk:loadTranslationTable{
  ["ofl_edition_ex"] = "线下珍藏",
  ["fhyx_ex"] = "飞鸿印雪",
  ["nineTP"] = "线下-九鼎", 
  ["ntp"] = "九鼎",
  ["ntp_mou"] = "九鼎·谋攻",
  }

local fhyx_ex__lingtong = General(extension, "fhyx_ex__lingtong", "wu", 4)
local fhyx__xuanfeng = fk.CreateTriggerSkill{   --旋风
  name = "fhyx__xuanfeng",
  anim_type = "control",
  events = {fk.AfterCardsMove, fk.EventPhaseEnd},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and table.every(player.room.alive_players, function(p) return not p.dying end) then
      if event == fk.AfterCardsMove then
        for _, move in ipairs(data) do
          if move.from == player.id then
            for _, info in ipairs(move.moveInfo) do
              if info.fromArea == Card.PlayerEquip then
                return table.find(player.room.alive_players, function (p)
                  return not p:isNude() and p ~= player or true
                end)
              end
            end
          end
        end
      elseif event == fk.EventPhaseEnd then
        if target == player and player.phase == Player.Discard and
        table.find(player.room.alive_players, function (p)
          return not p:isNude() and p ~= player or true
        end) then
          local x = 0
          local logic = player.room.logic
          logic:getEventsOfScope(GameEvent.MoveCards, 1, function (e)
            for _, move in ipairs(e.data) do
              if move.from == player.id and move.moveReason == fk.ReasonDiscard and move.skillName == "game_rule" then
                x = x + #move.moveInfo
                if x > 1 then return true end
              end
            end
            return false
          end, Player.HistoryTurn)
          return x > 1
        end
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = table.filter(room.alive_players, function(p) return not p:isNude() and p ~= player end)
    if not player.room:askForSkillInvoke(player, self.name) then 
      return false 
    end
    local choices_in = {}
    if #targets ~= 0 then
        table.insert(choices_in, "chaipai")
      end
    if room.current == player then 
        table.insert(choices_in, "zaxie")
      end
    if #choices_in == 2 then
        local choice = player.room:askForChoice(player, choices_in, self.name, nil, false, {"chaipai", "zaxie"}) --选择分支
        self.cost_data = choice
      elseif #choices_in == 1 then
        self.cost_data = choices_in[1] 
      else
        return false
      end
    return true
  end,

  on_use = function(self, event, target, player, data)
    local room = player.room
    local targets = table.filter(room.alive_players, function(p) return not p:isNude() and p ~= player end)
    if self.cost_data == "chaipai" then
      local tos = room:askForChoosePlayers(player, table.map(targets, Util.IdMapper), 1, 1, "#fhyx__xuanfeng-choose", self.name, true)
      if #tos > 0 then
        local to = room:getPlayerById(tos[1])
        local card = room:askForCardChosen(player, to, "he", self.name)
        room:throwCard({card}, self.name, to, player)
      end
      local targets = table.filter(room.alive_players, function(p) return not p:isNude() and p ~= player end)
      if player.dead then return false end  
      if #targets > 0 then
        local tos = room:askForChoosePlayers(player, table.map(targets, Util.IdMapper), 1, 1, "#fhyx__xuanfeng-choose", self.name, true)
        if #tos > 0 then
          table.insertIfNeed(targets, tos[1])
          to = room:getPlayerById(tos[1])
          card = room:askForCardChosen(player, to, "he", self.name)
          room:throwCard({card}, self.name, to, player)
          if player.dead then return false end
        end
      end
    end
      if self.cost_data == "zaxie" then   --造成伤害
        local targets_damage = table.filter(room.alive_players, function(p) return p ~= player end)
        local tos = room:askForChoosePlayers(player, table.map(targets_damage, Util.IdMapper), 1, 1, "#fhyx__xuanfeng-damage", self.name, true)
        if #tos > 0 then
          room:damage{
            from = player,
            to = room:getPlayerById(tos[1]),
            damage = 1,
            skillName = self.name,
          }
        end
      end
  end,
}


local fhyx__yongjin = fk.CreateActiveSkill{   --勇进
  name = "fhyx__yongjin",
  anim_type = "offensive",
  frequency = Skill.Limited,
  card_num = 0,
  target_num = 0,
  card_filter = Util.FalseFunc,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local excludeIds = {}
    for i = 1, 3, 1 do
      if #room:canMoveCardInBoard("e", nil, excludeIds) == 0 or player.dead then break end
      local to = room:askForChooseToMoveCardInBoard(player, "#fhyx__yongjin-choose", self.name, true, "e", false, excludeIds)
      if #to == 2 then
        local result = room:askForMoveCardInBoard(player, room:getPlayerById(to[1]), room:getPlayerById(to[2]), self.name, "e", nil, excludeIds)
        if result then
          table.insert(excludeIds, result.card:getEffectiveId())
        else
          break
        end
      else
        break
      end
    end
  end,
}
fhyx_ex__lingtong:addSkill(fhyx__xuanfeng)
fhyx_ex__lingtong:addSkill(fhyx__yongjin)
Fk:loadTranslationTable{
  ["fhyx_ex__lingtong"] = "凌统",
  ["#fhyx_ex__lingtong"] = "豪情烈胆",
  ["illustrator:fhyx_ex__lingtong"] = "聚一",
  ["fhyx__xuanfeng"] = "旋风",
  [":fhyx__xuanfeng"] = "当你失去装备区里的牌，或于弃牌阶段弃掉两张或更多的牌时，且没有角色处于濒死状态，你可以选择一项：1.依次弃置一至两名其他角色的共计两张牌；2.若此时是你的回合内，则你可以对一名其他角色造成1点伤害。",
  ["#fhyx__xuanfeng-choose"] = "旋风：你可以依次弃置一至两名其他角色的共计两张牌",
  ["#fhyx__xuanfeng-damage"] = "旋风：你可以对其中一名角色造成一点伤害。",
  ["chaipai"] = "弃置任意名其他角色共计至多两张牌",
  ["zaxie"] = "对一名其他角色造成1点伤害",
  ["fhyx__yongjin"] = "勇进",
  [":fhyx__yongjin"] = "限定技，出牌阶段，你可以依次移动场上至多三张装备牌。",
  ["#fhyx__yongjin-choose"] = "勇进：你可以移动场上的一张装备牌",

  ["$fhyx__xuanfeng1"] = "风动扬帆起，枪出敌军溃！",
  ["$fhyx__xuanfeng2"] = "御风而动，敌军四散！",
  ["$fhyx__yongjin1"] = "鏖兵卫主，勇足以却敌！",
  ["$fhyx__yongjin2"] = "勇不可挡，进则无退！",
  ["~fhyx_ex__lingtong"] = "泉下弟兄，统来也！",
}

--仁区机制
---@param room Room @ 房间
---@return integer[]
local function GetRenPile(room)
  room.tag["ren"] = room.tag["ren"] or {}
  return table.simpleClone(room.tag["ren"])
end

local function NotifyRenPile(room)
  room:sendLog{
    type = "#NotifyRenPile",
    arg = #GetRenPile(room),
    card = GetRenPile(room),
  }
  room:setBanner("@$RenPile", table.simpleClone(room.tag["ren"]))
end

---@param room Room @ 房间
---@param card integer|integer[]|Card|Card[] @ 要加入仁区的牌/id/intList
---@param skillName string @ 移动的技能名
---@param proposer integer @ 移动操作者的id
local function AddToRenPile(room, card, skillName, proposer)
  local ids = Card:getIdList(card)
  room.tag["ren"] = room.tag["ren"] or {}
  local add, remove = {}, {}
  local ren_cards = table.simpleClone(room.tag["ren"])
  local ren_limit = 6
  for i = 1, ren_limit do
    local id = ids[i]
    if not id then break end
    table.insert(ren_cards, id)
    table.insert(add, id)
  end
  if #ren_cards > ren_limit then
    for i = #ren_cards - ren_limit, 1, -1 do
      table.insert(remove, table.remove(room.tag["ren"], i))
    end
  end
  local moveInfos = {}
  if #add > 0 then
    table.insertTable(room.tag["ren"], add)
    table.insert(moveInfos, {
      ids = add,
      from = room.owner_map[add[1]],
      toArea = Card.Void,
      moveReason = fk.ReasonJustMove,
      skillName = skillName,
      moveVisible = true,
      proposer = proposer,
    })
    room:sendLog{
      type = "#AddToRenPile",
      arg = #add,
      card = add,
    }
  end
  if #remove > 0 then
    table.insert(moveInfos, {
      ids = remove,
      toArea = Card.DiscardPile,
      moveReason = fk.ReasonPutIntoDiscardPile,
      skillName = "ren_overflow",
      moveVisible = true,
    })
    room:sendLog{
      type = "#OverflowFromRenPile",
      arg = #remove,
      card = remove,
    }
  end
  if #moveInfos > 0 then
    room:moveCards(table.unpack(moveInfos))
  end

  NotifyRenPile(room)
end

---@param room Room @ 房间
---@param player ServerPlayer @ 获得牌的角色
---@param cid integer | integer[] | Card | Card[] @ 要获得的牌
---@param skillName string @ 技能名
local function GetCardFromRenPile(room, player, cid, skillName)
  skillName = skillName or ""
  cid = Card:getIdList(cid)
  if #cid == 0 then return end
  local move = {
    ids = cid,
    to = player.id,
    toArea = Card.PlayerHand,
    moveReason = fk.ReasonJustMove,
    proposer = player.id,
    moveVisible = true,
    skillName = skillName,
  }
  room.logic:trigger("fk.BeforeRenMove", nil, move)
  room:moveCards(move)
  room.logic:trigger("fk.AfterRenMove", nil, move)
  for _, id in ipairs(cid) do
    table.removeOne(room.tag["ren"], id)
  end
  room:sendLog{
    type = "#GetCardFromRenPile",
    from = player.id,
    arg = #cid,
    card = cid,
  }
  NotifyRenPile(room)
end

---@param room Room @ 房间
---@param player ServerPlayer @ 弃置牌的角色
---@param ids integer|integer[] @ 要弃置的id/idList
---@param skillName string @ 技能名
local function DiscardCardFromRenPile(room, player, ids, skillName)
  skillName = skillName or ""
  if type(ids) ~= "number" then
    ids = ids
  else
    ids = {ids}
  end
  if #ids == 0 then return end
  local move = {
    ids = ids,
    toArea = Card.DiscardPile,
    moveReason = fk.ReasonDiscard,
    proposer = player.id,
    moveVisible = true,
    skillName = skillName,
  }
  room.logic:trigger("fk.BeforeRenMove", nil, move)
  room:moveCards(move)
  room.logic:trigger("fk.AfterRenMove", nil, move)
  for _, id in ipairs(ids) do
    table.removeOne(room.tag["ren"], id)
  end
  room:sendLog{
    type = "#DiscardCardFromRenPile",
    from = player.id,
    arg = #ids,
    card = ids,
  }
  NotifyRenPile(room)
end

local liuzhang = General(extension, "fhyx_ex__liuzhang", "qun", 3)
local yinge = fk.CreateActiveSkill{
  name = "fhyx__yinge",
  anim_type = "offensive",
  target_num = 1,
  card_num = 0,
  prompt = "#fhyx__yinge-prompt",
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    return #selected == 0 and #Fk:currentRoom():getPlayerById(to_select):getCardIds(Player.Hand) > 0
  end,
  can_use = function(self, player)
    return not player.dead and player:hasSkill(self) and player:usedSkillTimes(self.name, HistoryPhase) == 0
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local card = room:askForCard(target, 1, 1, false, self.name, false, ".", "#yinge-ask") or {}
    if #card > 0 then
      AddToRenPile(room, card, self.name, target.id)
      local ren_cards = GetRenPile(room)
      local use = U.askForUseRealCard(room, target, ren_cards, ".|.|.|^(hand,equip)", self.name, "#yinge-use", {
        expand_pile = ren_cards,
      }, true)
      if use then
        if use.card.is_damage_card and table.contains(room:getUseExtraTargets(use, true), player.id) then
          table.insertIfNeed(use.tos, {player.id})
        end
        local moveInfo = {
          ids = {use.card.id},
          toArea = Card.Processing,
          moveReason = fk.ReasonJustMove,
          skillName = self.name,
          moveVisible = true,
          proposer = target.id,
        }
        room.logic:trigger("fk.BeforeRenMove", nil, move)
        room:moveCards(moveInfo)
        room.logic:trigger("fk.AfterRenMove", nil, move)
        room:sendLog{
          type = "#YingeUseCardFromRenPile",
          from = player.id,
          card = {use.card.id},
        }
        table.removeOne(room.tag["ren"], use.card.id)
        NotifyRenPile(room)
        room:useCard(use)
      end
    end
  end,
}
local shiren = fk.CreateTriggerSkill{
  name = "fhyx__shiren",
  anim_type = "defensive",
  events = {fk.TargetConfirmed},
  can_trigger = function(self, event, target, player, data)
    if player == target and player:hasSkill(self) and data.card then
      return data.card.is_damage_card and data.from ~= player.id
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local choices = {"shiren_drawpile", "shiren_drawcards", "#fhyx__shiren-cancel"}
    local choice = room:askForChoice(player, choices, self.name, "#fhyx__shiren-choose")
    self.cost_data = choice
    return choice == "shiren_drawpile" or choice == "shiren_drawcards"
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local choice = self.cost_data
    if choice == "shiren_drawpile" then
      local cids = room:getNCards(2, "top")
      AddToRenPile(room, cids, self.name)
      local ren_cids = GetRenPile(room)
      local cid = room:askForCard(player, 1, 1, false, self.name, false, ".|.|.|^(hand,equip)",  "#fhyx__shiren-obtain", ren_cids)
      if cid then
        GetCardFromRenPile(room, player, cid, self.name)
      end
    elseif choice == "shiren_drawcards" then
      player:drawCards(2, self.name)
      if #player:getCardIds(Player.Hand) > 0 then
        local cid = room:askForCard(player, 1, 1, false, self.name, false, ".", "#fhyx__shiren-select")
        if cid then
          AddToRenPile(room, cid, self.name, player.id)
        end
      end
    end
  end,
}
local juyi = fk.CreateTriggerSkill{
  name = "fhyx__juyi$",
  mute = true,

  refresh_events = {fk.EventAcquireSkill, fk.EventLoseSkill, fk.BuryVictim, fk.AfterPropertyChange},
  can_refresh = function(self, event, target, player, data)
    if event == fk.EventAcquireSkill or event == fk.EventLoseSkill then
      return data == self
    elseif event == fk.BuryVictim then
      return target:hasSkill(self, true, true)
    elseif event == fk.AfterPropertyChange then
      return target == player
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    local attached_huangtian = player.kingdom == "qun" and 
    table.find(room.alive_players, function (p)
      return p ~= player and p:hasSkill(self, true)
    end)
    if attached_huangtian and not player:hasSkill("fhyx__juyi_other&", true, true) then
      room:handleAddLoseSkills(player, "fhyx__juyi_other&", nil, false, true)
    elseif not attached_huangtian and player:hasSkill("fhyx__juyi_other&", true, true) then
      room:handleAddLoseSkills(player, "-fhyx__juyi_other&", nil, false, true)
    end
  end,
}
local juyi_other = fk.CreateTriggerSkill{
  name = "fhyx__juyi_other&",
  anim_type = "support",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Discard
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local card = room:askForCard(player, 1, 1, false, "fhyx__juyi$", true, ".", "#fhyx__juyi-ask") or {}
    if #card > 0 then 
      self.cost_data = card
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local owner = table.filter(room.alive_players, function(p)
      return p:hasSkill(Fk.skills["fhyx__juyi$"])
    end)[1]
    local cid = self.cost_data
    local over = {}
    room:notifySkillInvoked(player, juyi.name)
    owner:broadcastSkillInvoke(juyi.name)
    if #GetRenPile(room) == 6 then
      over = {GetRenPile(room)[1]}
    end
    AddToRenPile(room, cid, self.name, player.id)
    if #over > 0 and owner then
      if not owner.dead then
        room:obtainCard(owner, over, true, fk.ReasonJustMove, owner.id)
      end
    end
  end,
}
Fk:addSkill(juyi_other)
liuzhang:addSkill(yinge)
liuzhang:addSkill(shiren)
liuzhang:addSkill(juyi)
Fk:loadTranslationTable{
  ["fhyx_ex__liuzhang"] = "刘璋",
  ["#fhyx_ex__liuzhang"] = "求仁失益",
  ["illustrator:fhyx_ex__liuzhang"] = "鬼画府",
  ["fhyx__yinge"] = "引戈",
  [":fhyx__yinge"] = "出牌阶段限一次，你可以令一名角色将一张手牌置入“仁”区，然后其可以使用一张“仁”牌，其以此法使用伤害类的牌时，"..
  "若你不为此牌目标，则你成为此牌的额外目标。",
  ["#fhyx__yinge-prompt"] = "引戈：令一名角色将一张手牌置入“仁”区并使用一张“仁”区的牌",
  ["#YingeUseCardFromRenPile"] = "%from 使用了“仁”区的 %card",
  ["#yinge-ask"] = "引戈：你须选择一张手牌置入“仁”区",
  ["#yinge-use"] = "引戈：你可以使用“仁”区的一张牌",
  ["fhyx__shiren"] = "施仁",
  [":fhyx__shiren"] = "当你成为其他角色使用伤害类的牌的目标后，你可以选择一项：1.将牌堆顶的两张牌置入“仁”区，然后获得一张“仁”牌；"..
  "2.摸两张牌，然后将一张手牌置入“仁”区。",
  ["shiren_drawpile"] = "将牌堆顶两张牌置入“仁”区，然后获得“仁”区中的一张牌",
  ["shiren_drawcards"] = "摸两张牌，然后将一张手牌置入“仁”区",
  ["#fhyx__shiren-cancel"] = "取消",
  ["#fhyx__shiren-choose"] = "施仁：请选择一项",
  ["#fhyx__shiren-obtain"] = "施仁：获得“仁”区的一张牌",
  ["#fhyx__shiren-select"] = "施仁：选择一张手牌置入“仁区”",
  ["fhyx__juyi"] = "据益",
  [":fhyx__juyi"] = "主公技，其他群势力角色的弃牌阶段开始时，其可以将一张手牌置入“仁”区，然后若“仁”区因此法溢出，你获得溢出的“仁”牌。",
  ["fhyx__juyi_other&"] = "据益",
  [":fhyx__juyi_other&"] = "弃牌阶段开始时，你可以将一张手牌置入“仁”区，然后若“仁”区因此法溢出，拥有“据益”获得溢出的“仁”牌。",
  ["#fhyx__juyi-ask"] = "据益：你可以将一张手牌置入“仁”区",

  ["$fhyx__juyi1"] = "百姓安乐足矣，穷兵黩武实不可取啊。",
  ["$fhyx__juyi2"] = "内乱初定，更应休养生息。",
  ["$fhyx__yinge1"] = "益州疲敝，还望贤兄相助。",
  ["$fhyx__yinge2"] = "内讨米贼，外拒强曹，璋无宗兄万万不可啊。",
  ["$fhyx__shiren1"] = "哎！匹夫无罪，怀璧其罪啊。",
  ["$fhyx__shiren2"] = "粮草尽皆在此，宗兄可自取之。",
  ["~fhyx_ex__liuzhang"] = "引狼入室，噬脐莫及啊！",
}

--local zhangzhongjing = General(extension, "fhyx_ex__zhangzhongjing", "qun", 3)
local liaoyi = fk.CreateTriggerSkill{
  name = "fhyx_ex__liaoyi",
  anim_type = "control",
  events = {fk.TurnStart},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and target ~= player then
      local n = target:getHandcardNum() - target.hp
      return n ~= 0 and #GetRenPile(player.room) >= math.min(-n, 2)
    end
  end,
  on_cost = function(self, event, target, player, data)
    local n = target:getHandcardNum() - target.hp
    local prompt
    if n < 0 then
      prompt = "#fhyx_ex__liaoyi1-invoke::"..target.id..":"..math.min(-n, 2)
    else
      prompt = "#fhyx_ex__liaoyi2-invoke::"..target.id..":"..math.min(n, 2)
    end
    return player.room:askForSkillInvoke(player, self.name, nil, prompt)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:doIndicate(player.id, {target.id})
    local n = target:getHandcardNum() - target.hp
    if n < 0 then
      n = math.min(-n, 2)
      local all_cards = GetRenPile(room)
      local cards = U.askforChooseCardsAndChoice(target, all_cards, {"OK"}, self.name, "#fhyx_ex__liaoyi-choose:::"..n, nil, n, n, all_cards)
      GetCardFromRenPile(room, target, cards, self.name)
    else
      n = math.min(n, 2)
      local cards = room:askForCard(target, n, n, true, self.name, false, ".", "#fhyx_ex__liaoyi-put:::"..n)
      AddToRenPile(room, cards, self.name, target.id)
    end
  end,
}
local binglun = fk.CreateActiveSkill{
  name = "fhyx_ex__binglun",
  anim_type = "support",
  card_num = 1,
  target_num = 1,
  prompt = "#fhyx_ex__binglun",
  expand_pile = function () return Self:getTableMark("$RenPile") end,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and #player:getTableMark("$RenPile") > 0
  end,
  card_filter = function (self, to_select, selected)
    return #selected == 0 and table.contains(Self, "$RenPile"):getTableMark(to_select)
  end,
  target_filter = function(self, to_select, selected)
    return #selected == 0
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    DiscardCardFromRenPile(room, player, effect.cards, self.name)
    if target.dead then return end
    local choices = {"draw1", "binglun_recover"}
    local choice = room:askForChoice(target, choices, self.name)
    if choice == "draw1" then
      target:drawCards(1, self.name)
    else
      local mark = target:getTableMark(self.name)
      table.insert(mark, player.id)
      room:setPlayerMark(target, self.name, mark)
    end
  end,
}

--zhangzhongjing:addSkill("jishi")
--zhangzhongjing:addSkill(liaoyi)
--zhangzhongjing:addSkill(binglun)
Fk:loadTranslationTable{
  ["fhyx_ex__zhangzhongjing"] = "张仲景",
  ["#fhyx_ex__zhangzhongjing"] = "医理圣哲",
  ["illustrator:fhyx_ex__zhangzhongjing"] = "鬼画府",
  ["fhyx_ex__liaoyi"] = "疗疫",
  [":fhyx_ex__liaoyi"] = "其他角色回合开始时，若其手牌数小于体力值且场上“仁”数量不小于X，则你可以令其获得X张“仁”；若其手牌数大于体力值，"..
  "则可以令其将X张牌置入“仁”区（X为其手牌数与体力值差值，且至多为2）。",
  ["fhyx_ex__binglun"] = "病论",
  [":fhyx_ex__binglun"] = "出牌阶段限一次，你可以弃置一张“仁”牌并令一名角色回复1点体力。",
  ["#fhyx_ex__liaoyi1-invoke"] = "疗疫：你可以令 %dest 获得%arg张“仁”",
  ["#fhyx_ex__liaoyi2-invoke"] = "疗疫：你可以令 %dest 将%arg张牌置入“仁”区",
  ["#fhyx_ex__liaoyi-choose"] = "疗疫：获得%arg张“仁”区牌",
  ["#fhyx_ex__liaoyi-put"] = "疗疫：你需将%arg张牌置入“仁”区",
  ["#fhyx_ex__binglun"] = "病论：你可以弃置一张“仁”区牌，令一名角色回复1点体力",

  ["$jishi1"] = "勤求古训，常怀济人之志。",
  ["$jishi2"] = "博采众方，不随趋势之徒。",
  ["$fhyx_ex__liaoyi1"] = "麻黄之汤，或可疗伤寒之疫。",
  ["$fhyx_ex__liaoyi2"] = "望闻问切，因病施治。",
  ["$fhyx_ex__binglun1"] = "受病有深浅，使药有重轻。",
  ["$fhyx_ex__binglun2"] = "三分需外治，七分靠内养。",
  ["~fhyx_ex__zhangzhongjing"] = "得人不传，恐成坠绪……",
}

local simayan = General(extension, "ntp__simayan", "jin", 3)
local juqi = fk.CreateTriggerSkill{
  name = "ntp__juqi",
  switch_skill_name = "ntp__juqi",
  mute = true,
  anim_type = "switch",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    if player == target and player:hasSkill(self) and player.phase == Player.Start then
      return true
    elseif player ~= target and player:hasSkill(self) and target.phase == Player.Start then
      return not target:isKongcheng()
    end
  end,
  on_cost = function(self, event, target, player, data)
    if target == player then
      return true
    else
      local isYang = player:getSwitchSkillState(self.name) == fk.SwitchYang
      if not isYang then
        local cid = player.room:askForCard(target, 1, 1, false, self.name, true, ".|.|spade,club", "#ntp__juqi-black:"..player.id)
        if #cid > 0 then
          self.cost_data = cid
          return true
        end
      else
        local cid = player.room:askForCard(target, 1, 1, false, self.name, true, ".|.|heart,diamond", "#ntp__juqi-red:"..player.id)
        if #cid > 0 then
          self.cost_data = cid
          return true
        end
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local isYang = player:getSwitchSkillState(self.name) == fk.SwitchYang
    if not isYang then
      if player == target then
        player:broadcastSkillInvoke(self.name, 1)
        player.room:notifySkillInvoked(player, self.name, "switch")
        player:drawCards(3, self.name)
      else
        player:broadcastSkillInvoke(self.name, 4)
        player.room:notifySkillInvoked(player, self.name, "switch")
        local cid = self.cost_data
        if #cid > 0 then
          target:showCards(cid)
          player.room:obtainCard(player, cid, true, fk.ReasonGive, target.id)
        end
      end
    else
      if player == target then
        player:broadcastSkillInvoke(self.name, 2)
        player.room:notifySkillInvoked(player, self.name, "switch")
        player.room:setPlayerMark(player, "@@ntp__juqi_buff-turn", 1)
      else
        player:broadcastSkillInvoke(self.name, 3)
        player.room:notifySkillInvoked(player, self.name, "switch")
        local cid = self.cost_data
        if #cid > 0 then
          target:showCards(cid)
          player.room:obtainCard(player, cid, true, fk.ReasonGive, target.id)
        end
      end
    end
  end,
  refresh_events = {fk.DamageCaused},
  can_refresh = function(self, event, target, player, data)
    return target == player and player:getMark("@@ntp__juqi_buff-turn") > 0
  end,
  on_refresh = function(self, event, target, player, data)
    data.damage = data.damage + 1
    return
  end,
}
local juqi_buff = fk.CreateTargetModSkill{
  name = "#ntp__juqi_buff",
  bypass_times = function(self, player, skill, scope, card, to)
    return card and player:getMark("@@ntp__juqi_buff-turn") > 0
  end,
}
local taishi = fk.CreateTriggerSkill{
  name = "ntp__taishi$",
  anim_type = "special",
  frequency = Skill.Limited,
  events = {fk.BeforeTurnStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  on_use = function(self, event, target, player, data)
    local room = target.room
    for _, p in ipairs(room.alive_players) do
      if (p:getMark("__hidden_general") ~= 0 or p:getMark("__hidden_deputy") ~= 0) then
        room:doIndicate(player.id, {p.id})
        room:handleAddLoseSkills(p, "-"..self.name, nil, false, true)
        if Fk.generals[p:getMark("__hidden_general")] then
          p.general = p:getMark("__hidden_general")
        end
        if Fk.generals[p:getMark("__hidden_deputy")] then
          p.deputyGeneral = p:getMark("__hidden_deputy")
        end
        room:setPlayerMark(p, "__hidden_general", 0)
        room:setPlayerMark(p, "__hidden_deputy", 0)
        local general = Fk.generals[p.general]
        local deputy = Fk.generals[p.deputyGeneral]
        p.gender = general.gender
        p.kingdom = general.kingdom
        room:broadcastProperty(p, "gender")
        room:broadcastProperty(p, "general")
        room:broadcastProperty(p, "deputyGeneral")
        room:askForChooseKingdom({p})
        room:broadcastProperty(p, "kingdom")
        
        p.maxHp = p:getGeneralMaxHp()
        p.hp = deputy and math.floor((deputy.hp + general.hp) / 2) or general.hp
        p.shield = math.min(general.shield + (deputy and deputy.shield or 0), 5)
        local changer = Fk.game_modes[room.settings.gameMode]:getAdjustedProperty(p)
        if changer then
          for key, value in pairs(changer) do
            p[key] = value
          end
        end
        room:broadcastProperty(p, "maxHp")
        room:broadcastProperty(p, "hp")
        room:broadcastProperty(p, "shield")

        local lordBuff = p.role == "lord" and p.role_shown == true and #room.players > 4
        local skills = general:getSkillNameList(lordBuff)
        if deputy then
          table.insertTable(skills, deputy:getSkillNameList(lordBuff))
        end
        skills = table.filter(skills, function (s)
          local skill = Fk.skills[s]
          return skill and (#skill.attachedKingdom == 0 or table.contains(skill.attachedKingdom, p.kingdom))
        end)
        if #skills > 0 then
          room:handleAddLoseSkills(p, table.concat(skills, "|"), nil, false)
        end

        room:sendLog{ type = "#RevealGeneral", from = p.id, arg =  "mainGeneral", arg2 = general.name }
        local event_data = {["m"] = general}
        if deputy then
          room:sendLog{ type = "#RevealGeneral", from = p.id, arg =  "deputyGeneral", arg2 = deputy.name }
          event_data["d"] = deputy.name
        end
        room.logic:trigger("fk.GeneralAppeared", p, event_data)
      end
    end
  end,
}
juqi:addRelatedSkill(juqi_buff)
simayan:addSkill(juqi)
simayan:addSkill("fengtu")
simayan:addSkill(taishi)
local simayan_win = fk.CreateActiveSkill{ name = "ntp__simayan_win_audio" }
simayan_win.package = extension
Fk:addSkill(simayan_win)
Fk:loadTranslationTable{
  ["ntp__simayan"] = "司马炎",
  ["#ntp__simayan"] = "晋武帝",
  ["cv:ntp__simayan"] = "寂镜",
  ["illustrator:ntp__simayan"] = "鬼画府",

  ["ntp__juqi"] = "举棋",
  [":ntp__juqi"] = "转换技：①准备阶段，你摸三张牌/其他角色准备阶段，其可以展示并交给你一张黑色手牌；②准备阶段，令你本回合使用牌无次数限制且造成的伤害+1/其他角色的准备阶段，"..
  "其可以展示并交给你一张红色手牌。",
  ["@@ntp__juqi_buff-turn"] = "举棋：加伤",
  ["#ntp__juqi-black"] = "举棋：你可以展示并交给 %src 一张黑色手牌",
  ["#ntp__juqi-red"] = "举棋：你可以展示并交给 %src 一张红色手牌",
  ["ntp__fengtu"] = "封土",
  [":ntp__fengtu"] = "当一名其他角色死亡后，你可以令一名为未以此法减少过体力上限的角色减1点体力上限，然后其获得死亡角色位置每轮的额定回合。",

  --[[["@ntp__fengtu_record"] = "封土",
  ["#ntp__fengtu-choose"] = "封土：你可以选择一名未以此法选择过的角色，其减少1点体力上限，获得 %src 的额定回合",
  ["#GainSomeoneRealTurn"] = "%from 将执行 %arg2 %arg3 的额定回合",]]

  ["@fengtu"] = "封土",
  ["#fengtu-choose"] = "封土：你可令其中一名角色减1体力上限并获得%arg号位的额定回合",
  ["ntp__taishi"] = "泰始",
  [":ntp__taishi"] = "主公技，限定技，一名角色回合开始前，你可以令所有隐匿角色依次登场。",

  ["$ntp__juqi1"] = "事须从缓，养兵以待。",
  ["$ntp__juqi2"] = "即日伐吴，朕意已决。",
  ["$ntp__juqi3"] = "（交给牌）公闾之言字字珠玑，当养精蓄锐，以静制动。",
  ["$ntp__juqi4"] = "（交给牌）依元凯之疏，此时伐吴可显朕之威名，以定四海。",
  ["$fengtu_ntp__simayan1"] = "诸王镇疆，朕当无忧！",
  ["$fengtu_ntp__simayan2"] = "天予九鼎，地封九州！",
  ["$fengtu_ntp__simayan3"] = "普天之下，莫非皇土！",
  ["$ntp__taishi1"] = "大命加身，国泰兵兴！",
  ["$ntp__taishi2"] = "汉德既衰，晋祚始昌！",
  ["~ntp__simayan"] = "孝礼不彰，九鼎将崩......",
  ["$ntp__simayan_win_audio"] = "好戏才刚刚开始......",
}

local cardDic = UE.cardDic
local PrepareExtraCardPile = fk.CreateTriggerSkill{
  name = "PrepareExtraCardPile",
  mute = true,
  global = true,
  priority = 0.1,
  refresh_events = {fk.GamePrepared, fk.AfterCardsMove},
  can_refresh = function (self, event, target, player, data)
    if event == fk.AfterCardsMove then
      if player ~= player.room.current then return end
      local room = player.room
      for _, move in ipairs(data)do --拒绝沟槽的多重move
        local cids = {}
        if move.toArea == Card.Void then
          for _, info in ipairs(move.moveInfo) do
            local c = Fk:getCardById(info.cardId)
            if c:getMark("@@ExtraCard_Mark") > 0 then
              table.insert(cids, info.cardId)
            end
          end
          if #cids > 0 then
            self.cost_data = {"MoveIn", cids, move}
            return true
          end
        else
          for _, info in ipairs(move.moveInfo) do
            if info.fromArea == Card.Void and Fk:getCardById(info.cardId):getMark("@@ExtraCard_Mark") > 0
             and table.contains(UE.getExtraCardPile(room), info.cardId) then
              table.insert(cids, info.cardId)
            end
          end
          if #cids > 0 then
            self.cost_data = {"MoveOut", cids, move}
            return true
          end
        end
      end
    else
      return true
    end
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    if event == fk.AfterCardsMove then
      if self.cost_data[1] == "MoveIn" then
        local event_data = {
          cids = self.cost_data[2],
          moveData = self.cost_data[3]
        }
        local cids = UE.getExtraCardPile(room)
        for _, id in ipairs(self.cost_data[2]) do
          table.insertIfNeed(cids, id)
        end
        room:setTag("ExtraCardPile", cids)
        room:setBanner("@$ExtraCardPile", cids)
        room:sendLog{
          type = "#ExtraCardMovein",
          card = self.cost_data[2],
          arg = #self.cost_data[2],
        }
        room.logic:trigger("fk.AfterExtraCardMoveIn", nil, event_data)
      elseif self.cost_data[1] == "MoveOut" then
        local event_data = {
          cids = self.cost_data[2],
          moveData = self.cost_data[3]
        }
        local cids = UE.getExtraCardPile(room)
        for _, id in ipairs(self.cost_data[2]) do
          table.removeOne(cids, id)
        end
        room:setTag("ExtraCardPile", cids)
        room:setBanner("@$ExtraCardPile", cids)
        room:sendLog{
          type = "#ExtraCardMoveOut",
          card = self.cost_data[2],
          arg = #self.cost_data[2],
        }
        room.logic:trigger("fk.AfterExtraCardMoveOut", nil, event_data)
      end
    else
      U.prepareDeriveCards(room, cardDic, "ExtraCardPile")
      for _, id in ipairs(room:getTag("ExtraCardPile")) do
        room:setCardMark(Fk:getCardById(id), "@@ExtraCard_Mark", 1)
      end
      room:setBanner("@$ExtraCardPile", room:getTag("ExtraCardPile"))
    end
  end
}
Fk:addSkill(PrepareExtraCardPile)
Fk:loadTranslationTable{
  ["@$ExtraCardPile"] = "额外牌堆",
  ["@@ExtraCard_Mark"] = "额外牌",
  ["#ExtraCardMovein"] = "%arg 张牌 %card 被移入额外牌堆",
  ["#ExtraCardMoveOut"] = "%arg 张牌 %card 被移出额外牌堆",
}

return extension